package config

import (
	"encoding/json"
	"log"
	"os"
	"path/filepath"
)

type GithubRepo struct {
	Repo         string            `json:"repo"`
	FileTemplate string            `json:"file_template"`
	AppJson      map[string]string `json:"app.json"`
}

// 读取 github.json
func ReadRepo() (repoList map[string]GithubRepo) {
	if content, err := os.ReadFile(filepath.Join(DataDir, "github.json")); err != nil {
		log.Fatal(err)
	} else if err := json.Unmarshal(content, &repoList); err != nil {
		log.Fatal(filepath.Join(DataDir, "github.json"), err)
	}
	return
}

// 读取 github-local.json
func ReadVersion() (versionList map[string]string) {
	if content, err := os.ReadFile(filepath.Join(DataDir, "github-local.json")); err != nil {
		log.Print(err)
		versionList = make(map[string]string)
	} else if len(content) == 0 || string(content) == "null" {
		versionList = make(map[string]string)
	} else if err := json.Unmarshal(content, &versionList); err != nil {
		log.Fatal(filepath.Join(DataDir, "github-local.json"), err)
	}
	return
}

// 保存到 github-local.json
func SaveVersion(versionList map[string]string) {
	if content, err := json.MarshalIndent(versionList, "", "    "); err != nil {
		log.Fatal(err)
	} else if err := os.WriteFile(filepath.Join(DataDir, "github-local.json"), content, 0644); err != nil {
		log.Fatal(filepath.Join(DataDir, "github-local.json"), err)
	}
}
